package cn.frh.org.service.impl;

import cn.frh.basic.service.impl.BaseServiceImpl;
import cn.frh.basic.util.Md5Utils;
import cn.frh.basic.util.StrUtils;
import cn.frh.org.domain.Employee;
import cn.frh.org.mapper.EmployeeMapper;
import cn.frh.org.service.IEmployeeService;
import cn.frh.user.domain.Logininfo;
import cn.frh.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;


    @Autowired
    private LogininfoMapper logininfoMapper;


    @Override
    public void save(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String s = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(s);
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        logininfo.setDisable(true);

        logininfoMapper.save(logininfo);

        employee.setLogininfoId(logininfo.getId());
        super.save(employee);
        employeeMapper.saveEmployeeRole(employee);
    }

    @Override
    public void remove(Long id) {
        Employee employee = employeeMapper.loadById(id);
        logininfoMapper.remove(employee.getLogininfoId());
        employeeMapper.removeEmployeeRoleByEmployee(id);
        super.remove(id);
    }

    @Override
    public void update(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5 = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5);
        super.update(employee);

        Employee employee1 = employeeMapper.loadById(employee.getId());
        Long logininfoId = employee1.getLogininfoId();
        Logininfo logininfo = logininfoMapper.loadById(logininfoId);
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setId(logininfoId);
        logininfoMapper.update(logininfo);

        //删除中间表信息
        employeeMapper.removeEmployeeRoleByEmployee(employee.getId());
        //保存新的信息
        if(employee.getRoleId()!=null){
            employeeMapper.saveEmployeeRole(employee);
        }
    }

    @Override
    public List<Employee> findByShopId(Long shopId) {
        return employeeMapper.findByShopId(shopId);
    }
}
